<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="resetSearch">
      <x-filter-item :label="$t('auth.role.type')">
        <x-select
          :placeholder="$t('auth.role.typePlaceholder')"
          v-model="searchParams.roleType"
          :options="dictOptions['upms_role.role_type']"
          style="width: 100%"
        />
      </x-filter-item>
      <x-filter-item :label="$t('auth.role.name')">
        <el-input v-model="searchParams.roleName" :placeholder="$t('auth.role.namePlaceholder')" clearable></el-input>
      </x-filter-item>
    </x-filter>
    <!--数据面板-->
    <x-data>
      <!--数据面板按钮插糟-->
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button
              v-hasPermi="['upms:role:add']"
              type="primary"
              @click="handleAddRole()"
              :icon="buttonIcons('add')"
            >
              {{ $t('auth.role.new') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:role:state']"
              type="primary"
              @click="handleChangeState('0')"
              :icon="buttonIcons('other')"
            >
              {{ $t('auth.role.batchDisable') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:role:state']"
              type="primary"
              @click="handleChangeState('1')"
              :icon="buttonIcons('other')"
            >
              {{ $t('auth.role.batchEnable') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:role:exportRoles']"
              type="primary"
              @click="handleExportExcel('role')"
              :icon="buttonIcons('export')"
            >
              {{ $t('auth.role.exportRoles') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:role:exportMenus']"
              type="primary"
              @click="handleExportExcel('menu')"
              :icon="buttonIcons('export')"
            >
              {{ $t('auth.role.exportScopes') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:role:exportScops']"
              type="primary"
              @click="handleExportExcel('data')"
              :icon="buttonIcons('export')"
            >
              {{ $t('auth.role.exportData') }}
            </el-button>
            <el-button
              v-hasPermi="['upms:role:delete']"
              type="danger"
              @click="handleBatchDelete()"
              :icon="buttonIcons('delete')"
            >
              {{ $t('auth.role.batchDelete') }}
            </el-button>
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <!-- 数据表格 -->
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <el-switch
              v-if="item.prop === 'state'"
              :value="scope.row[item.prop]"
              active-color="#4474F6"
              inactive-color="#A5A9B2"
              @change="handleChangeRoleState(scope.row[item.prop], scope.row.id)"
              :disabled="!checkBntPermi('upms:role:state')"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
            <span v-else-if="item.prop === 'roleType'">{{
              getDictLabel(dictOptions['upms_role.role_type'], scope.row[item.prop])
            }}</span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
          <template #default="scope">
            <more-table-actions
              :action-list="getActions(actions, scope.row)"
              :permis-list="permissionsActions"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
    <role-add ref="roleAddComponent" :dict-options="dictOptions" @handleSuccess="loadData"></role-add>
  </x-page>
</template>
<script>
  import { buttonIcons, omit, PermissionsMixin, QueryDictMixin, selectDictLabel, TableListMixin } from '@package/utils'
  import { actions, columns } from '../config/roleConfig.js'
  import RoleAdd from '../components/roleAdd.vue'
  import {
    apiDeleteRole,
    apiPutBatchDisable,
    apiPutBatchEnable,
    apiRoleDataExportUrl,
    apiRoleExportUrl,
    apiRoleMenuExportUrl,
    pageRoleUrl
  } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    name: 'Role',
    components: {
      RoleAdd
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        buttonIcons,
        columns,
        actions,
        pageRoleUrl,
        apiRoleExportUrl,
        apiRoleMenuExportUrl,
        apiRoleDataExportUrl,
        searchParams: {
          roleName: '',
          roleType: ''
        },
        statusOptions: [],
        tableData: [],
        roleOptions: [],
        isVisible: false,
        params: {
          ids: [],
          reason: '',
          state: ''
        },
        // title: '启用角色',
        dictKeys: ['system.state', 'upms_role.role_type']
      }
    },
    computed: {
      listUrl() {
        return this.pageRoleUrl
      },
      getActions() {
        return (actions, row) => {
          return actions.map((action) => {
            action.disabled = ['delete', 'edit'].indexOf(action.key) !== -1 && row.preset === 1
            return action
          })
        }
      }
    },
    methods: {
      getDictLabel(list, value) {
        return selectDictLabel(list, value) || '-'
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'delete':
            this.handleBatchDelete(data.id)
            break
          case 'edit':
            this.$refs.roleAddComponent.handleOpen(data)
            break
          case 'auth':
            this.$router.push({ path: '/authManage/role/authorization', query: data })
            break
          default:
            break
        }
      },
      handleAddRole() {
        this.$refs.roleAddComponent.handleOpen()
      },
      handleChangeState(state) {
        if (!this.selectionRows.length) {
          this.$message.warning(this.$t('auth.role.selectionTips'))
          return
        }
        this.$confirm(
          state === 1 ? this.$t('auth.role.batchEnablePrmit') : this.$t('auth.role.batchDisablePromit'),
          this.$t('system.user.deletePrompt'),
          {
            confirmButtonText: this.$t('common.confirm'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }
        ).then(() => {
          const ids = this.selectionRows.map((v) => v.id)
          this.handleChangeRoleState(`${state}` === '0' ? '1' : '0', ids)
        })
      },
      async handleChangeRoleState(state, ids) {
        const result = Array.isArray(ids) ? ids : [ids]

        try {
          const { msg, code } = `${state}` === '1' ? await apiPutBatchDisable(result) : await apiPutBatchEnable(result)
          if (code === EnumApiCode.Success) {
            this.$message.success(this.$t('auth.role.successTips'))
            this.loadData()
          } else {
            this.$message.error(msg)
          }
        } finally {
          this.loadData()
        }
      },
      handleSubmit() {
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = {
              ...omit(this.params, 'state')
            }
            const { code, msg } =
              this.params.state === 1 ? await apiPutBatchEnable(param) : await apiPutBatchDisable(param)
            if (code === EnumApiCode.Success) {
              this.$refs.params.resetFields()
              this.$message.success(this.$t('auth.role.successTips'))
              this.handleClose()
              this.loadData()
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        })
      },
      handleClose() {
        this.$refs.params.resetFields()
        this.isVisible = false
      },
      handleExportExcel(type) {
        switch (type) {
          case 'role':
            this.handleExport(this.apiRoleExportUrl)
            break
          case 'menu':
            this.handleExport(this.apiRoleMenuExportUrl)
            break
          case 'data':
            this.handleExport(this.apiRoleDataExportUrl)
            break
          default:
            break
        }
      },
      handleBatchDelete(id) {
        if (!id && !this.selectionRows.length) {
          this.$message.warning(this.$t('auth.role.selectionTips'))
          return
        }
        this.$confirm(this.$t('auth.role.deletePrmo'), this.$t('auth.role.prompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          const ids = id || this.selectionRows.map((v) => v.id).join(',')
          this.handleDeleteRole(ids)
        })
      },
      async handleDeleteRole(id) {
        const { code, msg } = await apiDeleteRole(id)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('auth.role.successTips'))
          this.loadData()
        } else {
          this.$message.error(msg)
        }
      }
    }
  }
</script>
